package fragments;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import org.json.JSONException;
import org.json.JSONObject;

import ws.JSONManager;
import ws.JsonParsers;
import android.app.ActionBar.OnNavigationListener;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SpinnerAdapter;
import android.widget.Toast;

import com.cachopoid.R;
import com.cachopoid.activity.MainActivity;
import com.cachopoid.utils.CachopoBaseAdapter;
import com.cachopoid.utils.Constantes;
import com.cachopoid.utils.Utils;
import com.cachopoid.vo.CachopoVO;
import com.cachopoid.vo.EstablecimientoVO;


public class FragmentRankingCachopos extends Fragment implements OnNavigationListener {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";
    static ListView listViewRanking;
    static ArrayList<CachopoVO> listaRankingCachoposGlobal;
    static ArrayList<EstablecimientoVO> ListaRankingEstablecimientosGlobal;
    static ProgressBar pbarProgresoRanking;
    Constantes cons = new Constantes();
    static Context mContext;
    static JSONObject jsonResult = new JSONObject();

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static FragmentRankingCachopos newInstance(int sectionNumber,MainActivity mainActivity) {
    	FragmentRankingCachopos fragment = new FragmentRankingCachopos();
    	mContext = mainActivity.getBaseContext();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public FragmentRankingCachopos() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
    
        SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(this.getActivity().getBaseContext(),R.array.valores_spinner_ranking,
        		android.R.layout.simple_spinner_dropdown_item);
        android.app.ActionBar actionBar = getActivity().getActionBar();
        actionBar.setListNavigationCallbacks(mSpinnerAdapter, this);
        
    	View rootView = inflater.inflate(R.layout.fragment_rankingcachopos, container, false);
        listViewRanking = (ListView)rootView.findViewById(R.id.listaRanking);
        pbarProgresoRanking = (ProgressBar) rootView.findViewById(R.id.pbarProgresoRanking);
		//Se lanza el hilo para el ranking de cachopos si la lista esta vacía
   		if(listaRankingCachoposGlobal==null){
   			threadCargaRankingCachopos  threadRankingCachopos = new threadCargaRankingCachopos(container.getContext());
   		 	threadRankingCachopos.execute();
   		}
        
        
        //pbarProgreso = (ProgressBar) rootView.findViewById(R.id.pbarProgresoRanking);
       
        ArrayList<EstablecimientoVO> listaRankingEstablecimientosGlobal = new ArrayList<EstablecimientoVO>();
        
        ///Si ya esta llena la lista de cachopos y ya paso por el thread
        if(listaRankingCachoposGlobal!=null){
        	listViewRanking.setAdapter(new CachopoBaseAdapter(rootView.getContext(), listaRankingCachoposGlobal, ListaRankingEstablecimientosGlobal));
        }
        
		

		listViewRanking.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> a, View v, int position, long id) {
				
				Object objeto = listViewRanking.getItemAtPosition(position);
				
				//Si es el ranking de cachopos se recupera el establecimiento para mostrar su detalle
				EstablecimientoVO establecimientoVO = new EstablecimientoVO();
				CachopoVO cachopoVO = new CachopoVO();
				if(objeto.getClass().isInstance(cachopoVO)){
					cachopoVO = (CachopoVO)objeto;					
					establecimientoVO.setIdEstablecimiento(cachopoVO.getIdEstablecimiento());
					objeto=Utils.devuelveElEstablecXCachopo(ListaRankingEstablecimientosGlobal,listaRankingCachoposGlobal,establecimientoVO,position);
				}
				
				EstablecimientoVO establecimiento = (EstablecimientoVO)objeto;
				
				
				 FragmentManager fragmentManager = getFragmentManager();
				fragmentManager.beginTransaction()
	            .replace(R.id.container, FragmentDetalleCachopos.newInstance(position + 1,cachopoVO,v,establecimiento))
	            .addToBackStack(null)
	            .commit();


			} 
		});
        return rootView;

    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((MainActivity) activity).onSectionAttached(
                getArguments().getInt(ARG_SECTION_NUMBER));
    }

	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		if(listaRankingCachoposGlobal!=null){
		   switch (itemPosition) {
		   //Mejor Cachopo
 		    case 0:
 		    	Collections.sort(listaRankingCachoposGlobal, new Comparator<CachopoVO>() {
 		    		public int compare(CachopoVO ch1, CachopoVO ch2) {
 		    			return new Double(ch2.getMediaDeVotos()).compareTo(new Double(ch1.getMediaDeVotos()));
 		    		}
 		    	});
 		    	
 		    break;
 		   //Mas votado
 		    case 1:
 		    	Collections.sort(listaRankingCachoposGlobal, new Comparator<CachopoVO>() {
 		    		public int compare(CachopoVO ch1, CachopoVO ch2) {
 		    			return new Double(ch2.getTotal_votos()).compareTo(new Double(ch1.getTotal_votos()));
 		    		}
 		    	});

 		    break;
 		   //Calidad-Precio
 		    case 2:
 		    	Collections.sort(listaRankingCachoposGlobal, new Comparator<CachopoVO>() {
 		    		public int compare(CachopoVO ch1, CachopoVO ch2) {
 		    			return new Double(ch2.getPrecio()).compareTo(new Double(ch1.getPrecio()));
 		    		}
 		    	});
 		    	
 		    break;
 		   //Mejor Sabor
 	        case 3:
 				Collections.sort(listaRankingCachoposGlobal, new Comparator<CachopoVO>() {
 		    		public int compare(CachopoVO ch1, CachopoVO ch2) {
 		    			return new Double(ch2.getSabor()).compareTo(new Double(ch1.getSabor()));
 		    		}
 		    	});
 	 	    break;
 	 	    //Mayor tamaño
 		    case 4:
 				Collections.sort(listaRankingCachoposGlobal, new Comparator<CachopoVO>() {
 		    		public int compare(CachopoVO ch1, CachopoVO ch2) {
 		    			return new Double(ch2.getTamanio()).compareTo(new Double(ch1.getTamanio()));
 		    		}
 		    	});
 	 	    break;
 		   
 		   default:
 		   break;
 	    }
		   listViewRanking.setAdapter(new CachopoBaseAdapter(mContext, listaRankingCachoposGlobal, ListaRankingEstablecimientosGlobal));
		}
     return true;
     }
	
	  public class threadCargaRankingCachopos extends AsyncTask <Void, Integer, Boolean> {
	    	
	    	String urlRankingCachopos = cons.HOST_SERVICIOWEB+cons.SW_OBTENER_CACHOPOS_ORDERBY_BEST;
//	    	LayoutInflater l_Inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//			View convertView = l_Inflater.inflate(R.layout.activity_lista, null);
	    	//ProgressBar pbarProgreso = (ProgressBar) mContext.findViewById(R.id.pbarProgresoRanking);
	    

	    	

			public threadCargaRankingCachopos(Context context) {
				mContext =context;
			}

			@Override
	    	protected Boolean doInBackground(Void... params) {
	    		
	    	      try{
	    	    	  pbarProgresoRanking.setVisibility(View.VISIBLE);
	    	    	  JSONManager jManager = new JSONManager();
	    	    	 jsonResult = jManager.getJSONfromURL(urlRankingCachopos,null);
	    	     }catch(Exception e){
	    	    	 
	    	     }
	    	      
	    	     return true;
	    	}
	    	
	    	@Override
	    	protected void onProgressUpdate(Integer... values) {
	 //   		 int progreso = values[0].intValue();
//	    		 pbarProgreso.setProgress(progreso);
	    	}
	    	
	    	@Override
	    	protected void onPreExecute() {
//	    		pbarProgreso.setMax(100);
//	    		pbarProgreso.setProgress(0);
	    	}
	    	
	    	@Override
	    	protected void onPostExecute(Boolean result) {
	    		if(result){
	    			
	    			try {
	    				if(jsonResult != null){
	    					listaRankingCachoposGlobal=JsonParsers.parseJSONCachopos(jsonResult.getJSONArray("cachopos"));
	    					ListaRankingEstablecimientosGlobal=JsonParsers.parseJSONEstablecimientos(jsonResult.getJSONArray("establecimientos"));
	    					listViewRanking.setAdapter(new CachopoBaseAdapter(mContext, listaRankingCachoposGlobal, ListaRankingEstablecimientosGlobal));
	    				}
	    				
	    				
	    			} catch (JSONException e) {
	    				e.printStackTrace();
	    			}
	    			pbarProgresoRanking.setVisibility(View.GONE);
	    			Toast.makeText(mContext, "Carga finalizada!", Toast.LENGTH_SHORT).show();
	    			
	    		}
	    	}
	    	
	    	@Override
	    	protected void onCancelled() {
	    		Toast.makeText(mContext, "Carga cancelada!", Toast.LENGTH_SHORT).show();
	    	}
	    }
}